
//
// Copyright 2009 Arne Halvorsen (arne.halvorsen@gmail.com)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

// Project page: http://code.google.com/p/webfg/

//
// 091201 - aha42 - Created.
//

package org.aha.webfg;

import static org.aha.servlet.ParameterUtil.getMandatoryParameter;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.aha.mf4j.FlickrUrls;
import org.aha.mf4j.response.FlickrObject;

/**
 * <p>
 *   Default 
 *   {@link WebfgPageCreator} implementation.
 * </p>
 * @author Arne Halvorsen (aha42)
 */
public class DefaultWebfgPageCreator extends AbstractWebfgPageCreator 
{
  /**
   * <p>
   *   Constructor.
   * </p>
   */
  public DefaultWebfgPageCreator(){}

  @Override
  public void handleFrontReq(HttpServletRequest req, HttpServletResponse resp)
    throws IOException 
  {
    //String nsid=req.getParameter("nsid");
    String nsid=WebfgUtil.getNsid(req, m_fs);
    
    String gid=req.getParameter("gid");
    
    FlickrObject galleryFo=WebfgUtil.getCollection(m_fc, nsid, gid);
    //FlickrObject[] forest=m_fc.getCollectionTrees(null, nsid);
    //FlickrObject galleryFo=new LookupVisitor().matchType("collection")
    //  .matchAttribute("id", gid).search(forest);
    
    if (galleryFo==null)
    {
      if (gid==null)
      {
        doDataAccessError("Can't find collection named 'Gallery'", resp);
      }
      else
      {
        doDataAccessError("Can't find collection with id : "+gid, resp);
      }
      return;
    }
    
    gid=galleryFo.getMandatoryAttribute("id");
    
    String title=galleryFo.getAttribute("title");
    title=(title==null) ? "Unnamed" : title;
    
    FlickrObject[] exhibitionFos=galleryFo.getChildren("set");
    int n=exhibitionFos.length;
    
    Map<String, String> tags=new HashMap<String, String>();
    
    String profileCode=null;
    FlickrObject profile=WebfgUtil.findProfileSet(exhibitionFos);
    if (profile!=null)
    {
      String sid=profile.getMandatoryAttribute("id");
      
      FlickrObject[] photos=WebfgUtil.getProfilePhotos(m_fc, m_fs, sid, tags);
      
      FlickrObject portrait=WebfgUtil.getRandomObject(photos);
      if (portrait!=null)
      {
        profileCode=createPlainPhotoHtml(portrait, nsid);
        
        String gtitle=tags.get("webfg.gallery-title");
        if (gtitle!=null) title=gtitle;
      }
    }
      
    /*
    String profileCode=null;
    FlickrObject profile=WebfgUtil.findProfileSet(exhibitionFos);
    if (profile!=null)
    {
      FlickrObject portrait=WebfgUtil.findProfilePhoto(m_fc,
        profile.getMandatoryAttribute("id"));
      if (portrait!=null)
      {
        profileCode=createPlainPhotoHtml(portrait, nsid);
        
        Map<String, String> tags=TagUtil.getNameValueTags(m_fs, 
          portrait.getAttribute("id"));
        String gtitle=tags.get("gallery-title");
        if (gtitle!=null) title=gtitle;
      }
    }
    */
    
    String license=WebfgUtil.getLicenseHtml(tags.get("webfg.license"));
    
    //
    // HTML CONSTRUCTION STARTS.
    //
    
    StringBuilder sb=htmlStart();
    
    sb.append("<h1 class='galleryTitle'>").append(title).append("</h1>");
    
    sb.append("<p>");
    
    if (profileCode!=null)
    {
      sb.append("<div>");
      sb.append(profileCode);
      sb.append("</div>");
    }
    
    sb.append("<div class='tocall'>");
    
    if (n>0)
    {
      for (int i=0; i<n; i++)
      {
        FlickrObject curr=exhibitionFos[i];
        
        title=curr.getAttribute("title");
        title=(title==null) ? "Unnamed" : title;
        if (!title.equals("profile"))
        {
          String exid=curr.getMandatoryAttribute("id");
          String url=getPieceUrl(exid, nsid, gid, -1, license);
          sb.append("<a class='toc' href='").append(url)
            .append("'> {").append(title).append("}</a>");
        }
      }
    }
    
    sb.append("</div>");
    
    sb.append("</p>");
    
    sb.append("<br/><br/><br/><br/>");
    sb.append("<p class='info'>&nbsp;&nbsp;&nbsp;").append(license)
      .append("</p>");
    
    String about=tags.get("webfg.about");
    String contact=tags.get("webfg.contact");
    if (about!=null || contact!=null)
    {
      if (about!=null)
      {
        String profileUrl=FlickrUrls.createProfileUrlSpec(nsid);
        sb.append("<p class='info'>&nbsp;&nbsp;&nbsp;<a href='")
          .append(profileUrl).append("'>").append(about).append("</a></p>");
      }
      if (contact!=null)
      {
        sb.append("<p class='info'>&nbsp;&nbsp;&nbsp;<a href='mailto:")
          .append(contact).append("'>contact</a></p>");
      }
    }
    
    sb.append("<br/><br/><br/><br/><p class='about'>")
      .append("<a href='/webfg>about service</a></p>");
    
    htmlEnd(sb, resp);
    
  }

  @Override
  public void handlePieceReq(HttpServletRequest req, HttpServletResponse resp)
    throws IOException 
  {
    StringBuilder sb=htmlStart();
    
    String nsid=getMandatoryParameter("nsid", req);
    String gid=getMandatoryParameter("gid", req);
    
    // Get all photos.
    String exid=req.getParameter("exid"); // Mandatory.
    FlickrObject[] pieceFos=m_fc.getPhotosInSet(exid, null, null, null);
    
    // Decide which piece:
    String idxP=req.getParameter("idx"); // Default.
    int idx=(idxP==null) ? 0 : Integer.parseInt(idxP);
    
    // Insert picture.
    FlickrObject curr=pieceFos[idx];
    String code=createPieceHtml(curr, nsid, exid, "m");
    sb.append("<p class='piece'>").append(code).append("</p>");
    
    String licenseEnc=req.getParameter("l");
    
    String license=(licenseEnc==null) ? null : 
      URLDecoder.decode(licenseEnc, "UTF-8");
    
    String licenseTxt=WebfgUtil.getLicenseHtml(license);
    
    sb.append("<p class='plicense'>").append(licenseTxt).append("</p>");
    
    int n=pieceFos.length;
    if (n>1)
    {
      sb.append("<p>");
      
      int leftIdx=(idx==0) ? n-1 : idx-1;
      sb.append("<div class='left'><a href='")
        .append(getPieceUrl(exid, nsid, gid, leftIdx, licenseEnc))
        .append("'>left</a>").append("</div>");
      
      int rightIdx=(idx==n-1) ? 0 : idx+1;
      sb.append("<div class='right'><a href='")
        .append(getPieceUrl(exid, nsid, gid, rightIdx, licenseEnc))
        .append("'>right</a>").append("</div>");
      
      sb.append("<div class='leave'><a href='webfg?where=front&nsid=")
        .append(nsid).append("&gid=").append(gid).append("'>leave</a></div>");
      
      sb.append("</p>");
    }
    
    htmlEnd(sb, resp);
    
  }
  
}
